<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
    <style>
      .imgdiv {
        width: 224px;
        height: 160px;
        border: 1px #ccc solid;
        display: inline-block;
        margin: 10px auto;
        margin-right: 100px;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <div><input v-focus /></div>
      <div v-img-lazy-load="item.url" v-for="item in list" class="imgdiv"></div>
    </div>

    <script>
      // 注册一个全局自定义指令 `v-focus`
      Vue.directive("focus", {
        // 当被绑定的元素插入到 DOM 中时……
        inserted: function(el) {
          // 聚焦元素
          el.focus();
        }
      });

      //图片加载前用随机色渲染
      Vue.directive("img-lazy-load", {
        // 当被绑定的元素插入到 DOM 中时……
        inserted: function(el, binding) {
          var color = Math.floor(Math.random() * 1000000);
          el.style.backgroundColor = "#" + color;

          var img = new Image();
          img.src = binding.value;
          img.onload = function() {
            el.style.background =
              "url(" +
              "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1512130636119&di=ad6017afe8acd3a305806b638c43bb93&imgtype=0&src=http%3A%2F%2Fi1.hdslb.com%2Fbfs%2Fface%2Fdd2336fbbb9b976179eae07fb0eaa66e0c5f34b1.gif" +
              ") no-repeat center center";
          };

          setTimeout(() => {
            var img = new Image();
            img.src = binding.value;
            img.onload = function() {
              el.style.backgroundImage = "url(" + binding.value + ")";
            };
          }, 1000);
        }
      });

      // 创建根实例
      new Vue({
        el: "#app",
        data: {
          list: [
            {
              url:
                "http://pic4.40017.cn/line/admin/2016/12/27/17/PW941D_224x160_00.jpg"
            },
            {
              url:
                "http://pic3.40017.cn/line/admin/2015/09/30/11/2oPhmn_224x160_00.jpg"
            }
          ]
        }
      });
    </script>
  </body>
</html>
